import socket


class fs_Client:
    def __init__(self, host="127.0.0.1", port=8888):
        """初始化客户端"""
        self.host = host
        self.port = port
        self.client_socket = None

    def connect(self):
        """连接服务器"""
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect((self.host, self.port))
        print(f"已连接到服务器 {self.host}:{self.port}")

    def send_command(self, command):
        """发送命令并接收响应"""
        if not self.client_socket:
            raise RuntimeError("未连接到服务器")

        # 发送命令
        self.client_socket.send(command.encode("utf-8"))

        # 接收响应
        response = self.client_socket.recv(1024)
        return response.decode('utf-8')

    def disconnect(self):
        """断开连接"""
        if self.client_socket:
            self.client_socket.close()
            self.client_socket = None


if __name__ == "__main__":
    client = fs_Client()

    try:
        client.connect()

        while True:
            msg = input("请输入命令（输入 'exit' 退出）: ")
            if msg.lower() == "exit":
                break
            elif msg == '':
                continue

            response = client.send_command(msg)
            print(f"服务器响应: {response}")

    except Exception as e:
        print(f"客户端错误: {e}")
    finally:
        client.disconnect()